/**
 * Project: shuyin-sync
 * 
 * File Created at Apr 5, 2012
 * $Id$
 * 
 * Copyright 2008 6677bank.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * 6677bank Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with 6677bank.com.
 */
package com.bank6677.sync.csm;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.bank6677.common.exception.BusinessException;
import com.bank6677.sync.csm.domain.Application;
import com.bank6677.sync.csm.service.ApplicationSyncService;

/**
 * TODO Comment of ApplicationSyncExecutor
 * 
 * @author liyue
 * @version ApplicationSyncExecutor.java Apr 5, 2012 2:18:06 PM
 */
public class ApplicationSyncExecutor extends Thread implements SynchronizeExecutor {

    private Integer                totalAppNum     = 0;                                              //需要同步的总数
    private Integer                currentStartApp = 0;                                              //每次循环开始的基数值
    private Integer                peroSyncAppNum  = 100;                                             //每次批量插入的量

    private ApplicationSyncService appSync;

    private List<Application>      syncApps;

    private List<Application>      currentSyncApps;

    private static Logger          LOG             = Logger.getLogger("sync.error");

    public ApplicationSyncExecutor() {
        System.out.println(getName());;
        appSync = SyncExecutor.getCtx().getBean("applicationSyncServiceImpl", ApplicationSyncService.class);
    }

    public ApplicationSyncExecutor(List<Application> apps) {
        this();
        syncApps = apps;
        totalAppNum = CollectionUtils.size(apps);
    }

    /*
     * (non-Javadoc)
     * @see com.bank6677.sync.csm.SynchronizeExecutor#execute()
     */
    @Override
    public void execute() {

    }

    @Override
    public void run() {
        ;
        for (; currentStartApp < totalAppNum;) {
            currentSyncApps = syncApps.subList(currentStartApp, currentStartApp + peroSyncAppNum);
            try {
                appSync.syncApplicationsWithTransaction(currentSyncApps);
            } catch (BusinessException e) {
                LOG.error("[" + StringUtils.join(currentSyncApps, ",") + "] is failed.", e);
            } finally {
                currentStartApp += peroSyncAppNum;
            }
        }
    }
}
